<template>

    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>
            <a href="/">基础数据</a>
        </el-breadcrumb-item>
        <el-breadcrumb-item>管理员设置</el-breadcrumb-item>
    </el-breadcrumb>


    <!-- 查询区域 -->

    <div style="padding: 12px; margin-top: 10px; border: 1px solid black;">

        <!-- <forminline></forminline>  行内表单-->

        <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="部门名称">
                <el-input v-model="formInline.DepartMentName" placeholder="请输入部门名称" clearable />
            </el-form-item>
            <el-form-item label="账号">
                <el-input v-model="formInline.AccountName" placeholder="请输入账号" clearable />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="search">搜索</el-button>
            </el-form-item>
        </el-form>
    </div>
    <!-- {{ tableData }} -->
    <div style="padding: 12px; margin-top: 10px; border: 1px solid black;">
        <el-button type="primary" @click="addDialog = true">新增</el-button>
        <el-table :data="tableData" style="width: 100%">
            <el-table-column type="index" label="序号" width="150" />
            <el-table-column label="头像" width="150">
                <template #default="scope">
                    <img style="width: 120px; height: 120px;" :src="scope.row.img">
                </template>
            </el-table-column>

            <el-table-column prop="realName" label="姓名" width="120" />
            <el-table-column prop="phoneNo" label="手机号" width="120" />
            <el-table-column prop="cardId" label="身份证号" width="180" />
            <el-table-column prop="roleName" label="角色" width="150" />
            <el-table-column prop="departmentName" label="所属部门" width="150" />
            <el-table-column fixed="right" label="操作" min-width="120">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="openDialog(scope.row)">
                        修改头像
                    </el-button>

                    <el-button type="danger" v-if="scope.row.roleName != '超级管理员' && scope.row.roleName != '系统管理员'"
                        size="small" @click="del(scope.row)">
                        删除
                    </el-button>

                    <el-button type="danger" v-if="scope.row.roleName != '超级管理员' && scope.row.roleName != '系统管理员'"
                        size="small" @click="toEdit(scope.row)">
                        编辑
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize"
            :page-sizes="[3, 4, 5, 6]" layout="total, sizes, prev, pager, next, jumper" :total="page.totalCount" />

    </div>



    <!-- 弹窗,弹出层 -->

    <el-dialog v-model="dialogVisible" title="修改" width="600">
        <!-- {{ id }}-{{ imageUrl }} -->

        <el-upload class="avatar-uploader" action="http://localhost:5141/api/Upload/Img" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
                <Plus />
            </el-icon>
        </el-upload>
        <el-button type="primary" @click="updateAccount()">确认</el-button>

    </el-dialog>

    <!-- 新增对话框,一定要放在页面 -->
    <el-dialog v-model="addDialog" title="新增管理员" width="600">
        {{ ruleForm }}
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="部门名称" prop="departmentId">

 <el-cascader v-model="ruleForm.departmentId" :options="options" :props="props" />
            </el-form-item>

            <el-form-item label="姓名" prop="realName">
                <el-input v-model="ruleForm.realName" />
            </el-form-item>
            <el-form-item label="身份号" prop="cardId">
                <el-input v-model="ruleForm.cardId" />
            </el-form-item>
            <el-form-item label="联系方式" prop="phoneNo">
                <el-input v-model="ruleForm.phoneNo" @blur="setAccount()" />
            </el-form-item>
            <el-form-item label="账号" prop="accountName">
                <el-input v-model="ruleForm.accountName" />
            </el-form-item>

            <el-form-item label="角色" prop="roleId">
                <el-select v-model="ruleForm.roleId" placeholder="" disabled="true">
                    <el-option label="超级管理员" :value="1" />
                    <el-option label="系统管理员" :value="2" />
                    <el-option label="网格长" :value="3" />
                    <el-option label="网格员" :value="4" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    保存
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>


    </el-dialog>


</template>


<script lang="ts" setup>
import axios from 'axios';
import { onMounted, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus';
import router from '@/router';
import type { FormInstance, FormRules } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import { useCounterStore } from '@/stores/counter';
import http from '@/http/axiosHelper';
const pinia = useCounterStore();

//options 级联的数据源
const options = ref([])  //我们要调用api 给级联数据源赋值
const getOptions = () => {
    http.get('/T5/Department/GetDepartmentTree').then(res => {
        options.value = res.data.data
    });
}
const props = {//这是级联的属性
    value: 'id',
    label: 'departmentName',
    children: 'children',
    checkStrictly: true,//选中任意节点
    emitPath: false //绑定节点的值,而不是各级菜单的值所组成的数组
};


// 新增对话框
const addDialog = ref(false) //添加弹窗是否显示
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
    "accountName": "",
    "realName": "",
    "cardId": "",
    "phoneNo": "",
    "departmentId": 0,
    "roleId": 1,
    "creator": pinia.loginDto.accountName,
    "img": "http://localhost:5141/pic/46A3A8EB6E2AAE753FFC0655E6942CB9.jpg"
}) //从后端接口文档中复制

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules>({
    departmentId: [
        { required: true, message: '请选择部门', trigger: 'blur' },
    ],
    realName: [
        {
            required: true,
            message: '请输入姓名',
            trigger: 'blur',
        },
        { min: 2, max: 10, message: '姓名长度应为2-10位', trigger: 'blur' },
    ],
    cardId: [
        {
            required: true,
            message: '身份证号不能为空',
            trigger: 'blur',
        },
        { min: 18, max: 18, message: '身份证号应为18位', trigger: 'blur' }
    ],
    phoneNo: [
        {
            required: true,
            message: '手机号不能为空',
            trigger: 'blur',
        },

        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确格式的手机号', trigger: 'blur' }
    ], accountName: [
        {
            required: true,
            message: '账号不能为空',
            trigger: 'blur',
        },
        { min: 2, max: 18, message: '账号长度应为2-18位', trigger: 'blur' }
    ],
})

const setAccount = () => {
    if (ruleForm.accountName.length == 0) {//账号需要手动输入，如果不输入，默认为手机号
        ruleForm.accountName = ruleForm.phoneNo
    }
}

//提交保存数据
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            axios.post('http://localhost:5150/api/Account/CreateAccount', ruleForm).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.msg);   //提示操作成功
                    addDialog.value = false;//关闭对话框
                    search();       //刷新数据
                    //清理表单对象
                    ruleForm.accountName = "";
                    ruleForm.realName = "";
                    ruleForm.cardId = "";
                    ruleForm.phoneNo = "",
                    ruleForm.departmentId = 0;
                    ruleForm.roleId = 0;
                    ruleForm.creator = "";
                } else {

                    ElMessage.error(res.data.msg);   //提示操作失败
                }

            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}


//删除
const del = (row: any) => {
    //调用http接口
}

//去编辑(打开弹窗,反填数据)
const toEdit = (row: any) => {
    //下节课继续....

}




const imageUrl = ref('')
const id = ref(0);
//上传成功之后,把file里的数据进行回填
const handleAvatarSuccess = (file: any) => {
    console.log(file);
    imageUrl.value = file.data
}


//校验图片
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('您的头像只能是jpg格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图像大小不得超过2兆!')
        return false
    }
    return true
}


const dialogVisible = ref(false)
const openDialog = (row: any) => {
    console.log("行数据:", row)

    imageUrl.value = row.img ?? 'http://localhost:5141/pic/default.jpg'
    id.value = row.id
    //反填
    dialogVisible.value = true;
}

const updateAccount = () => {
    //   ElMessage.error("更新接口正在开发中");
    // axios.put('http://localhost:5150/api/Account/UpadateAccountImg', {
    //     "id": id,
    //     "img": imageUrl
    // })
    axios.put('http://localhost:5150/api/Account/UpadateAccountImg', {
        "id": id.value,
        "img": imageUrl.value
    }).then(res => {
        if (res.data.code == 200) {
            ElMessage.success(res.data.msg);
            dialogVisible.value = false;
            search();
        } else {
            ElMessage.error(res.data.msg);
        }
    })
}


const formInline = reactive({
    DepartMentName: '',
    AccountName: '',
})

const page = reactive({
    PageIndex: 1,
    PageSize: 3,
    totalCount: 0
})

watch(page, () => {
    search();
})
const tableData = ref([])

//
const search = async () => {

    try {
       
        const res = await http.get('http://localhost:5141/api/Account/GetAccountPage', {
            params: {
                AccountName: formInline.AccountName,
                DepartMentName: formInline.DepartMentName,
                PageIndex: page.PageIndex,
                PageSize: page.PageSize
            }
        });

        if (res.data.code == 200) {
            tableData.value = res.data.pageDatas
            page.totalCount = res.data.totalCount
        }
    } catch (error) {
        if (error.response.status == 401) {//如果401访问token过期,去刷新token

            const rescode = await refreshToken();
            if (rescode == 200) {//刷新的结果是200,才能再次调用自己
                search();
            }
        }
    }

}

//http://localhost:5141/api/Account/RefreshToken
const refreshToken = async () => {
    try {

        const res = await axios.get('http://localhost:5141/api/Account/RefreshToken',
            { params: { RefreshToken: pinia.loginDto.refreshToken, FingerPoint: navigator.userAgent } })
        if (res.data.code == 200) {
            //把用户登录信息存起来
            pinia.loginDto.accountName = res.data.data.accountName
            pinia.loginDto.jwtToken = res.data.data.jwtToken
            pinia.loginDto.realName = res.data.data.realName
            pinia.loginDto.refreshToken = res.data.data.refreshToken
            pinia.loginDto.roleName = res.data.data.roleName
            return 200

        } else {//如果状态不是200,说明没有过去到访问token
            ElMessage.error(res.data.msg);
            router.push('/')

            return 500
        }

    } catch (error) {//刷新token出现异常,提示返回信息后,跳转到登录页
        ElMessage.error(error.response.data);
        router.push('/')
    }
}

onMounted(() => {
    search();
    getOptions();
})
</script>

<style>
.demo-form-inline .el-input {
    --el-input-width: 220px;
}

.demo-form-inline .el-select {
    --el-select-width: 220px;
}
</style>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>